package com.qlm.controller;

import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.qlm.interceptor.AdminOperate2Interceptor;
import com.qlm.interceptor.AdminOperateInterceptor;
import com.qlm.service.IAuthService;
import com.qlm.service.impl.AuthServiceImpl;
import com.qlm.tools.MyCaptchaRender;
import com.qlm.view.AdminView;

public class AuthController extends Controller {
	protected final static Logger logger = LoggerFactory
			.getLogger(AuthController.class);

	private IAuthService adminService = enhance(AuthServiceImpl.class);

	// 用户名正则
	private static final String REGEX = "^[a-zA-Z0-9]+$";

	/**
	 * 登陆处理
	 */
	public void login() {
		getSession().invalidate();
		AdminView adminView = getBean(AdminView.class, "adminView");
		String username = adminView.getUsername();
		if (username == null || adminView.getPassword() == null) {
			render("/page/login.jsp");
			return;
		}
		Pattern p = Pattern.compile(REGEX);
		boolean flg = p.matcher(username).matches();
		if (!flg) {
			setSessionAttr("message", "用户名中包含非法字符");
			render("/page/login.jsp");
			return;
		}

//		String inputRandomCode = getPara("captcha");
//		boolean validate = MyCaptchaRender.validate(this, inputRandomCode);
//		if (!validate) {
//			setSessionAttr("message", "验证码有误");
//			render("/page/login.jsp");
//			return;
//		}
		AdminView admin = adminService.login(adminView);
		if(admin==null) {
			setSessionAttr("message", "密码有误");
			render("/page/login.jsp");
		}else if (admin != null && admin.getStatus()==0) {
			setSessionAttr("message", "用户被禁用，请联系超级管理员！");
			render("/page/login.jsp");
		} else {
			setSessionAttr("adminView", admin);
			redirect("/index");
		}
	}

	public void index() {// 没登录时，不能到index页面要返回到登录页面
		AdminView admin = getSessionAttr("adminView");
		if (admin != null) {
			render("/page/menu.jsp");
		} else {
			render("/page/login.jsp");
		}

	}

	/**
	 * 退出处理
	 */
	public void logout() {
		getSession().invalidate();
		render("/page/login.jsp");
	}

	/**
	 * 原密码验证
	 */
	@Before({AdminOperateInterceptor.class,AdminOperate2Interceptor.class})
	public void pwdCheck() {
		AdminView av = getSessionAttr("adminView");
		boolean flg = adminService.pwdCheck(av.getUsername(),
				getPara("oldPassword"));
		if (flg) {
			renderText("success");
		}
	}

	/**
	 * 修改密码
	 */
	@Before({AdminOperateInterceptor.class,AdminOperate2Interceptor.class})
	public void updPwd() {
		AdminView av = getSessionAttr("adminView");
		AdminView adminView = new AdminView();
		adminView.setId(av.getId());
		adminView.setOldPwd(getPara("oldPwd"));
		adminView.setPassword(getPara("newPwd"));
		renderJson(adminService.adminUpd(adminView));
	}

	public void AuthImage() {
		render(new MyCaptchaRender(100, 34, 4, true));
	}
}
